package com.yj.netty.chapter04;

import com.yj.netty.chapter02.User;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

public class CustomEncoder extends MessageToByteEncoder <User>{
    @Override
    protected void encode(ChannelHandlerContext ctx, User user, ByteBuf out) throws Exception {

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream outputStream = new ObjectOutputStream(bos);
            outputStream.writeObject(user);


            byte[] bytes = bos.toByteArray();

            // 根据协议组装数据
            out.writeInt(1); // 数据标识
            out.writeByte(1); // 数据指令
            out.writeInt(bytes.length); // 数据长度
            out.writeBytes(bytes); // 数据内容
            ctx.channel().writeAndFlush(out);


            outputStream.flush();
            outputStream.close();
            bos.close();

    }

}
